from django.conf.urls import url
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action

from AnalysisService.util.Log import log

from AnalysisService import settings
from AnalysisService.util.DAMathUtil import CaptchaUtil, PhoneNumberUtil
from AnalysisService.util.DAResultJson import DAResultNoraml, DAResultCommon, DAResultCaptcha
from .captcha_models import AYCaptchaModel
from .captcha_serializers import AYCaptchaSerializer, AYCaptchaSendSerializer, AYCaptchaNoticeSerializer
# from .ay_db.captcha.AYCaptchaDB import CaptchaDB


class AYCaptchaSendView(ListModelMixin, GenericViewSet):
    queryset = AYCaptchaModel.objects.all()
    serializer_class = AYCaptchaSendSerializer

    @action(methods=['post'], detail=True)
    def obtainSMS(self, request):
        """
            获取验证码
        """
        data = request.data
        phonenumber = str(data['phonenumber'])

        try:

            isCheck = PhoneNumberUtil.check(phonenumber)

            if not isCheck:
                return DAResultCommon.phoneNumberFail()

            checkCode = CaptchaUtil.toStr()
            db = CaptchaDB()

            isbool = db.checkTime(phonenumber, settings.QMYIZ_CAPTCHA_OBTION_TIME)

            if not isbool:
                return DAResultCaptcha.wait()

            handler = MessageHandler()
            isbool = handler.send(phonenumber, checkCode)

            if not isbool:
                return DAResultNoraml.fail()

            isbool = db.add(phonenumber, checkCode)

            if not isbool:
                return DAResultCaptcha.fail()

            return DAResultCaptcha.success()
        except Exception as e:
            log.e('phonenumber: {}'.format(phonenumber), str(e))
            return DAResultNoraml.fail()

    @staticmethod
    def url_array():
        return url(r'^captcha-send/', AYCaptchaSendView.as_view({'post': 'obtainSMS', 'get': 'list'}),
                   name='captcha-send')


class AYCaptchaCheckView(ListModelMixin, GenericViewSet):
    queryset = AYCaptchaModel.objects.all()
    serializer_class = AYCaptchaSerializer

    def get(self, request):
        return self.list(request)

    def queryCaptcha(self, request):
        """
            验证 短信验证码
        """

        data = request.data
        phonenumber = data['phonenumber']
        captcha = data['captcha']

        try:

            if not settings.QMYIZ_TEST_CAPTCHA_CODE.__eq__(captcha):

                db = CaptchaDB()

                isbool = db.checkCode(phonenumber, captcha)

                if not isbool:
                    return DAResultCaptcha.checkFail()

                isbool = db.checkTime(phonenumber, settings.QMYIZ_CAPTCHA_TIME_OUT)

                if isbool:
                    return DAResultCaptcha.timeout()

            return DAResultCaptcha.checkSuccess()

        except Exception as e:
            log.e(e.args)
            return DAResultNoraml.fail()

    @staticmethod
    def url_array():
        return url(r'^captcha-check/',
                   AYCaptchaCheckView.as_view({'get': 'list', 'post': 'queryCaptcha'}),
                   name='captcha-check')


class AYCaptchaNoticeView(ListModelMixin, GenericViewSet):
    queryset = AYCaptchaModel.objects.all()
    serializer_class = AYCaptchaNoticeSerializer

    def get(self, request):
        return self.list(request)

    def sendNotice(self, request):
        """
            发送 通知短信
        """

        data = request.data
        phonenumber = data['phonenumber']
        name = data['name']
        smscode = data['smscode']

        isCheck = PhoneNumberUtil.check(phonenumber)

        if not isCheck:
            return DAResultCommon.phoneNumberFail()

        try:

            handler = MessageHandler()
            isbool = handler.sendNotice(phonenumber, name, 'SMS_152548522')

            if not isbool:
                return DAResultNoraml.fail()

            return DAResultCaptcha.noticeSuccess()

        except Exception as e:
            log.e(e.args)
            return DAResultNoraml.fail()

    @staticmethod
    def url_array():
        return url(r'^captcha-notice/',
                   AYCaptchaNoticeView.as_view({'get': 'list', 'post': 'sendNotice'}),
                   name='captcha-notice')
